package com.servlet;

import com.entity.Users;
import com.service.UsersService;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.jasypt.util.text.StrongTextEncryptor;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

@WebServlet("/register")
public class AdminGegisterServlet extends HttpServlet {
    private StrongPasswordEncryptor strongPasswordEncryptor;
    private StrongTextEncryptor textEncryptor;

    private UsersService usersService;
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        this.strongPasswordEncryptor = new StrongPasswordEncryptor();
        this.textEncryptor=new StrongTextEncryptor();
        this.usersService=new UsersService();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/register.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Users users = new Users();
        users.setUsername(req.getParameter("username"));

        String password = req.getParameter("password");
        users.setPwdHash(password);

        users.setSex(req.getParameter("gender"));
        String birthday = req.getParameter("birthday");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date= null;
        java.sql.Date sqlDate=null;
        try {
            date = format.parse(birthday);
            sqlDate = new java.sql.Date(date.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        users.setBirthday(sqlDate);



        String usertype = req.getParameter("typeOrAuthor");
        long type =0;
        if(usertype.equals("读者")){
            type=1L;
        }else if(usertype.equals("图书管理员")){
            type=2L;
        }else {
            type=3L;
        }
        users.setUsertype(type);
        users.setIsfull("正常");
        users.setMoney(0.0);
        Users register = null;
        try {
            register = usersService.add(users);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(Objects.nonNull(register)){
            req.setAttribute("user",register);
            req.getRequestDispatcher("/admin.jsp").forward(req,resp);
        }else {
            req.getRequestDispatcher("/register").forward(req,resp);
        }
    }
}



















